<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/12/24 0024
 * Time: 13:21
 */

namespace app\api\controller\product;

use app\admin\model\WarehouseGeneral;
use app\api\model\ProductReview;
use app\common\model\ProductOrderSpell;
use app\common\model\ProductSpell as ProductSpellService;
use app\Validate\PageMustValidate;
use think\Controller;
use think\Request;

/**
 * 拼团业务端方法类
 * Class ProductSpell
 * @package app\admin\controller\shop
 */
class ProductSpell extends Controller{
    /**
     * 获取拼团商品列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\lib\exception\ParameterException
     * @throws \think\exception\DbException
     */
    public function getProductSpellList(Request $request){
        (new PageMustValidate())->goCheck();
        $post = $request->post();
        /*
         * Select
            om_product_spell.id,
            om_product_spell.cover_img,
            om_product_spell.spell_name,
            om_product_spell.batch_num,
            om_product_spell.spell_price,
            om_product_spell.sales_num,
            om_product.product_price_one,
            FROM_UNIXTIME(om_product_spell.start_time) as start_time,
            FROM_UNIXTIME(om_product_spell.end_time) as end_time,
            DATE_FORMAT(FROM_UNIXTIME(om_product_spell.start_time),'%Y') as year,
            DATE_FORMAT(FROM_UNIXTIME(om_product_spell.start_time),'%u') as month
            from om_product_spell
            inner join om_product on om_product_spell.product_id = om_product.id
            where om_product_spell.is_show = 1 and om_product.is_publish = 2
            order by end_time desc
         */
        $where[] = ["om_product_spell.is_show","eq","1"];
        $where[] = ["om_product.is_publish","eq","2"];
        $productSpellService = new ProductSpellService();
        $field = "om_product_spell.id,
            om_product_spell.cover_img,
            om_product_spell.spell_name,
            om_product_spell.batch_num,
            om_product_spell.spell_price,
            om_product_spell.sales_num,
            om_product_spell.spell_num,
            om_product.product_price_one,
            DATE_FORMAT(FROM_UNIXTIME(om_product_spell.start_time),'%m.%d') as start_time,
            DATE_FORMAT(FROM_UNIXTIME(om_product_spell.end_time),'%m.%d')as end_time,
            YEAR(FROM_UNIXTIME(om_product_spell.start_time)) as year,
            MONTH(FROM_UNIXTIME(om_product_spell.start_time)) as month
            ";
        $list = $productSpellService->field($field)->where($where)
            ->join("om_product","om_product_spell.product_id = om_product.id")
            ->order("om_product_spell.start_time","desc")
            ->whereNull("om_product_spell.delete_time")
            ->paginate($post['page_number'], false, ['page' => $post['page']]);
        return writeJson(200,$list);
    }

    /**
     * 获取拼团订单详情
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getProductSpell(Request $request){
        $post = $request->post();
        if(!isset($post["spell_id"])){
            return writeJson(200,"缺少id","缺少id",10000);
        }
        //查询商品信息
        $productSpellService = new ProductSpellService();
        $model = $productSpellService->isExistsById($post["spell_id"]);
        if($model == null){ return writeJson(200,"当前拼团商品不存在","当前拼团商品不存在",10000);}

        //轮播图解码
        $img_path_arr = serializeMysql($model['img_path'],1);
        $img_path = [];
        foreach ($img_path_arr as $k=>$v){
            array_push($img_path,imgUrlToAbsolute($v));
        }
        $model['img_path'] = $img_path;


        //查询所有仓库剩余库存
        /**
         * select sum(stock) from om_warehouse_general where product_id = 2238
         */
        $count = (new WarehouseGeneral())->where(["product_id"=>$model["product_id"]])->sum("stock");
        $model["stock"] = $count;
        $model["description"] = (new \app\api\model\Product())->getProductDescription($model["product_id"]);

        //查询当前商品评论
        /**
         * select
        om_product_review.content,
        phone,
        FROM_UNIXTIME(om_product_review.create_time) as create_time
        from om_product_review
        inner join om_user on om_product_review.user_id = om_user.id
        where type = 3 and order_id = 2
         */
        $reviewWhere["type"] = 3;
        $reviewWhere["order_id"] = $model["id"];
        $productReviewService = new ProductReview();
        $list = $productReviewService
            ->field("om_product_review.content, phone, om_product_review.create_time")
            ->join("om_user","om_product_review.user_id = om_user.id")
            ->where($reviewWhere)
            ->order("create_time desc")->limit(5)->select()->toArray();

        //查询当前拼团情况
        /**
         * select
        om_product_order_spell.id,
        om_user.phone,
        om_user.nickname,
        ifNull(a.now_num,0) as now_num
        from om_product_order_spell
        inner join om_user on om_product_order_spell.user_id = om_user.id
        left join (select parent_id,count(parent_id) as now_num from om_product_order_spell where om_product_order_spell.product_spell_id group by parent_id) as a on om_product_order_spell.id = a.parent_id
        left join om_product_spell on om_product_order_spell.product_spell_id = om_product_spell.id
        where
        om_product_order_spell.product_spell_id = 2
        and om_product_order_spell.`status` = 1
        and om_product_order_spell.parent_id = 0
        and (now_num + 1 < om_product_spell.spell_num)
        and om_product_order_spell.user_id <> 615
         */
        $productSpellOrderService = new ProductOrderSpell();
        $spellOrderField = 'om_product_order_spell.id,om_user.phone,om_user.nickname,ifNull(a.now_num,0) as now_num';
        $spellOrderWhere["om_product_order_spell.product_spell_id"] = $model["id"]; //当前商品
        $spellOrderWhere["om_product_order_spell.status"] = 1;                      //未成团的
        $spellOrderWhere["om_product_order_spell.parent_id"] = 0;                   //所有团长
        $spellList = $productSpellOrderService
            ->field($spellOrderField)
            ->join("om_user","om_product_order_spell.user_id = om_user.id")
            ->join("(select parent_id,count(parent_id) as now_num from om_product_order_spell where om_product_order_spell.product_spell_id = ".$model['id'] ." and om_product_order_spell.status in (0,1) and `om_product_order_spell`.`delete_time` IS NULL group by parent_id) as a ","om_product_order_spell.id = a.parent_id","left")
            ->join("om_product_spell","om_product_order_spell.product_spell_id = om_product_spell.id")
            ->where($spellOrderWhere)
            ->where("( ifNull( a.now_num, 0 ) + 1 < om_product_spell.spell_num)")
            ->whereNull("om_product_order_spell.delete_time")
            ->limit(3)
            ->select()->toArray();

        foreach ($spellList as $k=>$v){
            $spellList[$k]["phone"] = substr_replace( $v["phone"], '****', 3, 4);
            $spellList[$k]["res_num"] = $model["spell_num"] - $v["now_num"] - 1; //除去团长自己
            $spellList[$k]["now_num"] = $v["now_num"] + 1;  //加上团长自己
        }

        //查询未成团的总人数
        $spellCount = $productSpellOrderService->where($spellOrderWhere)->count();

        //组合
        $result = array(
            "model"=>$model->toArray(),
            "review"=>$list,
            "spellCount"=>$spellCount,
            "spell"=>$spellList
        );
        return writeJson(200,$result);
    }

    /**
     * 获取当前拼团商品所有团
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\lib\exception\ParameterException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getOrderSpellList(Request $request){
        (new PageMustValidate())->goCheck();
        $post = $request->post();
        if(!isset($post["spell_id"])){ return writeJson(200,"缺少id","缺少id",10000);}

        //查询商品
        $productSpellService = new ProductSpellService();
        $where["om_product_spell.id"] = $post["spell_id"];
        $where["om_product_spell.is_show"] = 1;
        $where["om_product.is_publish"] = 2;
        $model = $productSpellService
            ->join("om_product","om_product_spell.product_id = om_product.id")
            ->where($where)->find();

        //查询当前拼团情况
        /**
         * select
        om_product_order_spell.id,
        om_user.phone,
        om_user.nickname,
        ifNull(a.now_num,0) as now_num
        from om_product_order_spell
        inner join om_user on om_product_order_spell.user_id = om_user.id
        left join (select parent_id,count(parent_id) as now_num from om_product_order_spell where om_product_order_spell.product_spell_id group by parent_id) as a
        on om_product_order_spell.id = a.parent_id
        where
        om_product_order_spell.product_spell_id = 2
        and om_product_order_spell.`status` = 0
        and om_product_order_spell.parent_id = 0
         */
        $productSpellOrderService = new ProductOrderSpell();
        $spellOrderField = 'om_product_order_spell.id,om_user.phone,om_user.nickname,ifNull(a.now_num,0) as now_num';
        $spellOrderWhere["om_product_order_spell.product_spell_id"] = $post["spell_id"];  //当前商品
        $spellOrderWhere["om_product_order_spell.status"] = 1;                      //未成团的
        $spellOrderWhere["om_product_order_spell.parent_id"] = 0;                   //所有团长

        $spellList = $productSpellOrderService
            ->field($spellOrderField)
            ->join("om_user","om_product_order_spell.user_id = om_user.id")
            ->join("(select parent_id,count(parent_id) as now_num from om_product_order_spell where om_product_order_spell.product_spell_id = ".$model['id'] ." and om_product_order_spell.status in (0,1) and `om_product_order_spell`.`delete_time` IS NULL group by parent_id) as a ","om_product_order_spell.id = a.parent_id","left")
            ->join("om_product_spell","om_product_order_spell.product_spell_id = om_product_spell.id")
            ->where($spellOrderWhere)
            ->where("( ifNull( a.now_num, 0 ) + 1 < om_product_spell.spell_num)")
            ->whereNull("om_product_order_spell.delete_time")
            ->paginate($post['page_number'], false, ['page' => $post['page']]);

        foreach ($spellList as $k=>$v){
            $spellList[$k]["phone"] = substr_replace( $v["phone"], '****', 3, 4);
            $spellList[$k]["res_num"] = $model["spell_num"] - $v["now_num"] - 1; //除去团长自己
            $spellList[$k]["now_num"] = $v["now_num"] + 1; //加上团长自己
        }

        return writeJson(200,$spellList);
    }
}